
package com.ziq.zcamp.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.Toast
import androidx.recyclerview.widget.GridLayoutManager
import com.donkingliang.groupedadapter.adapter.GroupedRecyclerViewAdapter
import com.donkingliang.groupedadapter.holder.BaseViewHolder
import com.ziq.base.base.BaseDialog
import com.ziq.base.extension.*
import com.ziq.zcamp.R
import com.ziq.zcamp.activities.ActivitiesDetailsViewModel
import com.ziq.zcamp.bean.product.ProductRepertoryItem
import com.ziq.zcamp.databinding.DialogPlaceProductPropertyBinding
import com.ziq.zcamp.databinding.ItemCalendarDateBinding
import com.ziq.zcamp.databinding.ItemCalendarMonthHeaderBinding
import com.ziq.zcamp.login.ActionAfterLogin
import com.ziq.zcamp.login.LoginActivity
import com.ziq.zcamp.manager.GlobalContextManager
import com.ziq.zcamp.util.TimeUtil
import com.ziq.zcamp.view.layoutmanager.CalendarGridLayoutManager
import kotlinx.coroutines.*
import java.text.DecimalFormat
import java.util.*

class ActivitiesProductPropertyDialog(context: Context,val mViewModel : ActivitiesDetailsViewModel) : BaseDialog(context) {

    private val binding: DialogPlaceProductPropertyBinding by binding()

    private var  adapter : MonthAdapter? = null
    var currentCount = 1
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window?.decorView?.let {
            window?.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE or WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
        }
        binding.root
        binding.btnClose.click {
            dismiss()
        }
        binding.btnNext.click {
            if(adapter?.selectedItem != null){
                LoginActivity.checkLogin(object : ActionAfterLogin {
                    override fun action() {
                        val info =  this@ActivitiesProductPropertyDialog.mViewModel.getSelectedTicket()
                        info?.let {
//                            ActivitiesConfirmActivity.open(context, it, currentCount, adapter?.selectedItem?.date, adapter?.selectedItem?.price?:0)
                        }
                    }
                })
            } else {
                Toast.makeText(GlobalContextManager.appContext, "请选择出行日期", Toast.LENGTH_SHORT).show()
            }
        }

        adapter = MonthAdapter(context)
        binding.rvMonth.adapter = adapter
        binding.rvMonth.layoutManager = CalendarGridLayoutManager(context, 7, adapter)

        binding.btnReduce.isEnabled = false
        binding.btnAdd.isEnabled = false
        binding.btnNext.isEnabled = false
        adapter?.onSelectedCallback = {
            currentCount = 1
            updateBookCount()
        }

        binding.btnReduce.setOnClickListener {
            if(currentCount > 1){
                currentCount--
            }
            updateBookCount()
        }

        binding.btnAdd.setOnClickListener {
            if(adapter?.selectedItem != null && adapter?.selectedItem!!.count > currentCount){
                currentCount++
            }
            updateBookCount()
        }

        setAnimateView(binding.root)
    }

    @SuppressLint("SetTextI18n")
    fun updateBookCount(){
        binding.btnReduce.isEnabled = currentCount != 1
        binding.btnAdd.isEnabled = adapter?.selectedItem != null && currentCount < adapter?.selectedItem!!.count
        binding.tvBookCount.text = "${currentCount}"
        if(adapter?.selectedItem != null){
            binding.btnNext.isEnabled = true
            val pay = (adapter?.selectedItem?.price?:0).toLong() * currentCount
            binding.tvPayPrice.text = DecimalFormat("0.00").format(pay / 100f)
            binding.tvStore.text = "库存${adapter?.selectedItem?.count}"
            binding.llPayPrice.visibility = View.VISIBLE
            binding.tvBookCount.setTextColor(Color.parseColor("#333333"))
        } else {
            binding.btnNext.isEnabled = false
            binding.tvStore.text = ""
            binding.tvPayPrice.text = ""
            binding.llPayPrice.visibility = View.INVISIBLE
            binding.tvBookCount.setTextColor(Color.parseColor("#999999"))
        }

    }

    private var scope : CoroutineScope? = null
    fun initData(list : MutableList<ProductRepertoryItem>){
        scope = CoroutineScope(Job() + Dispatchers.Main)
        if (scope==null)return
        scope!!.launch {
            val repertoryList : MutableMap<String,ProductRepertoryItem> = mutableMapOf()
            if (list.isNotEmpty()){
                for(item in list){
                    if(item.date_time != null){
                        repertoryList[item.date_time!!] = item
                    }
                }
            }
            val groupList: MutableList<MonthData> = mutableListOf()
            withContext(Dispatchers.Default){
                val today = TimeUtil.getTodayWithoutTime()
                var startDate = today.time
                var endDate = today.time
                if(repertoryList.isNotEmpty()){
                    val startDateString = repertoryList.keys.first()
                    val endDateString = repertoryList.keys.last()
                    TimeUtil.yyyy_MM_dd_DATE_FORMATTER.parse(startDateString)?.let {
                        startDate = it
                    }
                    TimeUtil.yyyy_MM_dd_DATE_FORMATTER.parse(endDateString)?.let {
                        endDate = it
                    }
                }
                if(startDate.before(today.time)){
                    startDate = today.time
                }
                if(endDate.before(today.time)){
                    endDate = today.time
                }

                val endCalendar = TimeUtil.calendar(endDate)
                val monthCount = TimeUtil.months(startDate, endCalendar.time)
                val currentMonth = TimeUtil.calendar(startDate)
                groupList.clear()
                var monthData: MonthData?
                for (i in 0..monthCount){
                    if(i != 0){
                        currentMonth.add(Calendar.MONTH, 1)
                    }
                    monthData = MonthData()
                    monthData.label = TimeUtil.yyyy_MM_DATE_FORMATTER_CN.format(currentMonth.time)
                    val position = TimeUtil.firstDayOfMonthIndex(currentMonth.time)
                    val dateCount = TimeUtil.maxDaysOfMonth(currentMonth.time)
                    if(position > 0){
                        for (index in 0 until position){
                            monthData.dateList.add(DateItem(true))
                        }
                    }

                    for (index in 1..dateCount){
                        currentMonth.set(Calendar.DAY_OF_MONTH, index)
                        val dateItem = DateItem()
                        dateItem.date = currentMonth.time
                        dateItem.isValidDate = today.time.time <= dateItem.date!!.time
                                && startDate.time <= dateItem.date!!.time
                                && dateItem.date!!.time <= endDate.time
                        if(dateItem.isValidDate){
                            val repertoryItem = repertoryList.get(TimeUtil.yyyy_MM_dd_DATE_FORMATTER.format(dateItem.date!!))

                            if(repertoryItem != null){
                                dateItem.price = repertoryItem.price
                                dateItem.count = repertoryItem.repertory_num?:0
                            } else {
                                dateItem.isValidDate = false
                                dateItem.price = null
                                dateItem.count = 0
                            }
                        }
                        monthData.dateList.add(dateItem)
                    }
                    groupList.add(monthData)
                }
            }
            adapter?.setData(groupList)
            updateBookCount()
        }
    }

    override fun dismiss() {
        scope?.cancel()
        super.dismiss()
    }

    override fun initWidth(): Int {
        return ViewGroup.LayoutParams.MATCH_PARENT
    }

    override fun initGravity(): Int {
        return Gravity.BOTTOM or Gravity.CENTER
    }

    private inner class MonthAdapter(context: Context) : GroupedRecyclerViewAdapter(context){
        var groupList: MutableList<MonthData> = mutableListOf()
        var selectedItem: DateItem? = null

        var onSelectedCallback : ((selectedItem: DateItem) -> Unit)? = null

        fun setData( groupList: MutableList<MonthData>) {
            selectedItem = null
            this.groupList = groupList
            notifyDataChanged()
            Log.e("测试","notifyDataChanged")
        }

        override fun getGroupCount(): Int {
            return groupList.size
        }

        override fun getChildrenCount(groupPosition: Int): Int {
            return groupList[groupPosition].dateList.size
        }

        override fun hasHeader(groupPosition: Int): Boolean {
            return true
        }

        override fun hasFooter(groupPosition: Int): Boolean {
            return false
        }


        override fun getHeaderLayout(viewType: Int): Int {
            return R.layout.item_calendar_month_header
        }

        override fun getChildLayout(viewType: Int): Int {
            return R.layout.item_calendar_date
        }

        override fun getFooterLayout(viewType: Int): Int {
            return 0
        }

        override fun onBindHeaderViewHolder(holder: BaseViewHolder?, groupPosition: Int) {
            holder?.let {
                val item = groupList[groupPosition]
                val binding = ItemCalendarMonthHeaderBinding.bind(holder.itemView)
                binding.tvMonth.text = "${item.label}"

                if(groupPosition == 0){
                    val lp = binding.root.layoutParams as GridLayoutManager.LayoutParams
                    lp.topMargin = 0
                    binding.root.layoutParams = lp
                }else {
                    val lp = binding.root.layoutParams as GridLayoutManager.LayoutParams
                    lp.topMargin = GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_24)
                    binding.root.layoutParams = lp
                }
            }
        }

        override fun onBindFooterViewHolder(holder: BaseViewHolder?, groupPosition: Int) {
        }

        override fun onBindChildViewHolder(
            holder: BaseViewHolder?,
            groupPosition: Int,
            childPosition: Int
        ) {
            holder?.let {
                val item = groupList[groupPosition].dateList[childPosition]
                val binding = ItemCalendarDateBinding.bind(holder.itemView)
                if(item.isEmpty || !item.isValidDate){
                    binding.root.click {}
                    binding.root.isSelected = false
                    binding.root.isEnabled = true
                    binding.tvPrice.isEnabled = true
                    binding.tvPrice.text = ""
                    binding.tvStatus.text = ""
                    binding.tvDate.isEnabled = false
                    binding.tvDate.text = ""
                    if(item.date != null){
                        binding.tvDate.text = "${TimeUtil.calendar(item.date!!).get(Calendar.DAY_OF_MONTH)}"
                    }
                } else {
                    binding.root.click {
                        selectedItem = item
                        onSelectedCallback?.invoke(item)
                        notifyDataChanged()
                    }

                    binding.root.isSelected = selectedItem != null && selectedItem == item

                    if(item.date != null){
                        binding.tvDate.text = "${TimeUtil.calendar(item.date!!).get(Calendar.DAY_OF_MONTH)}"
                    }
                    if(item.count > 0){
                        binding.root.isEnabled = true
                        binding.tvDate.isEnabled = true
                        binding.tvPrice.isEnabled = true
                        binding.tvPrice.text = "¥${DecimalFormat("0.00").format((item.price?:0) / 100f)}"
                        binding.tvStatus.text = ""
                    } else {
                        binding.root.isEnabled = false
                        binding.tvDate.isEnabled = false
                        binding.tvPrice.isEnabled = false
                        binding.tvPrice.text = ""
                        binding.tvStatus.text = "已订完"
                    }
                }

            }

        }

    }

    private inner class MonthData {
        var label:String? = null
        var dateList:MutableList<DateItem> = mutableListOf()
    }

    private inner class DateItem(empty :Boolean = false){
        var isEmpty = empty//补全第一天前的空格
        var date:Date? = null
        var price:Int? = null
        var count:Int = 0
        var isValidDate:Boolean = true
    }



}